<template>
  <el-dialog
    v-model="dialogVisible"
    title="分类统计信息"
    width="900px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div v-loading="loading" class="statistics-content">
      <!-- 基础统计 -->
      <div class="basic-statistics">
        <h3>基础统计</h3>
        <div class="stat-cards">
          <div class="stat-card">
            <div class="stat-value">
              {{ statistics?.total_categories || 0 }}
            </div>
            <div class="stat-label">总分类数</div>
          </div>
          <div class="stat-card enabled">
            <div class="stat-value">
              {{ statistics?.enabled_categories || 0 }}
            </div>
            <div class="stat-label">启用分类</div>
          </div>
          <div class="stat-card disabled">
            <div class="stat-value">
              {{ statistics?.disabled_categories || 0 }}
            </div>
            <div class="stat-label">禁用分类</div>
          </div>
          <div class="stat-card used">
            <div class="stat-value">{{ statistics?.used_categories || 0 }}</div>
            <div class="stat-label">已使用分类</div>
          </div>
          <div class="stat-card unused">
            <div class="stat-value">
              {{ statistics?.unused_categories || 0 }}
            </div>
            <div class="stat-label">未使用分类</div>
          </div>
        </div>
      </div>

      <!-- 状态分布 -->
      <div class="status-distribution">
        <h3>状态分布</h3>
        <div class="distribution-chart">
          <div
            v-for="item in statusDistribution"
            :key="item.status"
            class="distribution-item"
          >
            <div class="distribution-bar">
              <div
                class="bar-fill"
                :class="getStatusClass(item.status)"
                :style="{
                  width: getPercentage(item.count, totalCategories) + '%'
                }"
              />
            </div>
            <div class="distribution-info">
              <span class="status-name">{{ item.status_name }}</span>
              <span class="status-count">{{ item.count }}</span>
              <span class="status-percentage"
                >({{ getPercentage(item.count, totalCategories) }}%)</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 使用情况统计 -->
      <div class="usage-statistics">
        <h3>使用情况统计</h3>
        <div class="usage-table">
          <el-table :data="usageStatistics" stripe border>
            <el-table-column prop="name" label="分类名称" min-width="150">
              <template #default="{ row }">
                <div class="category-name">
                  <span>{{ row.name }}</span>
                  <el-tag
                    :type="CategoryManagementUtils.getStatusTagType(row.status)"
                    size="small"
                  >
                    {{ CategoryManagementUtils.getStatusText(row.status) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="total_articles"
              label="文章总数"
              width="100"
              align="center"
            >
              <template #default="{ row }">
                <span class="article-count">{{ row.total_articles }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="published_articles"
              label="已发布"
              width="80"
              align="center"
            >
              <template #default="{ row }">
                <span class="published-count">{{
                  row.published_articles
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="draft_articles"
              label="草稿"
              width="80"
              align="center"
            >
              <template #default="{ row }">
                <span class="draft-count">{{ row.draft_articles }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="latest_article_time"
              label="最新文章时间"
              width="180"
            >
              <template #default="{ row }">
                <span v-if="row.latest_article_time">{{
                  row.latest_article_time
                }}</span>
                <span v-else class="no-data">暂无文章</span>
              </template>
            </el-table-column>
            <el-table-column label="使用率" width="150" align="center">
              <template #default="{ row }">
                <div
                  class="usage-rate"
                  :class="{
                    'low-percentage':
                      getUsagePercentage(row.total_articles) < 20
                  }"
                >
                  <el-progress
                    :percentage="getUsagePercentage(row.total_articles)"
                    :color="getUsageColor(row.total_articles)"
                    :stroke-width="12"
                    :text-inside="getUsagePercentage(row.total_articles) >= 20"
                    :show-text="true"
                    :format="percentage => `${percentage}%`"
                  />
                  <span
                    v-if="getUsagePercentage(row.total_articles) < 20"
                    class="external-text"
                  >
                    {{ getUsagePercentage(row.total_articles) }}%
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="primary" @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import {
  getCategoryStatisticsApi,
  getCategoryStatusDistributionApi,
  getCategoryUsageStatisticsApi,
  type CategoryStatistics,
  type CategoryStatusDistribution,
  type CategoryUsageStatistics,
  CategoryManagementUtils
} from "@/api/category-management";

interface Props {
  visible: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
}>();

const dialogVisible = ref(false);
const loading = ref(false);
const statistics = ref<CategoryStatistics | null>(null);
const statusDistribution = ref<CategoryStatusDistribution[]>([]);
const usageStatistics = ref<CategoryUsageStatistics[]>([]);

// 监听对话框显示状态
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal) {
      loadStatistics();
    }
  },
  { immediate: true }
);

watch(dialogVisible, newVal => {
  emit("update:visible", newVal);
});

// 计算属性
const totalCategories = computed(() => {
  return statistics.value?.total_categories || 0;
});

// 方法
const loadStatistics = async () => {
  loading.value = true;
  try {
    // 并行加载所有统计数据
    const [statsData, distributionData, usageData] = await Promise.all([
      getCategoryStatisticsApi(),
      getCategoryStatusDistributionApi(),
      getCategoryUsageStatisticsApi()
    ]);

    if (statsData && statsData.code === 200) {
      statistics.value = statsData.data;
    }

    if (distributionData && distributionData.code === 200) {
      statusDistribution.value = distributionData.data;
    }

    if (usageData && usageData.code === 200) {
      usageStatistics.value = usageData.data;
    }
  } catch (error) {
    console.error("加载统计数据失败:", error);
    ElMessage.error("加载统计数据失败");
  } finally {
    loading.value = false;
  }
};

const getPercentage = (count: number, total: number): number => {
  if (total === 0) return 0;
  return Math.round((count / total) * 100);
};

const getStatusClass = (status: number): string => {
  return status === 1 ? "enabled" : "disabled";
};

const getUsagePercentage = (articleCount: number): number => {
  // 根据文章数量计算使用率，这里可以根据实际需求调整算法
  const maxArticles = Math.max(
    ...usageStatistics.value.map(item => item.total_articles),
    1
  );
  return Math.round((articleCount / maxArticles) * 100);
};

const getUsageColor = (articleCount: number): string => {
  const percentage = getUsagePercentage(articleCount);
  if (percentage >= 80) return "#67c23a";
  if (percentage >= 50) return "#e6a23c";
  if (percentage >= 20) return "#f56c6c";
  return "#909399";
};

const handleRefresh = () => {
  loadStatistics();
};

const handleClose = () => {
  dialogVisible.value = false;
};

// 生命周期
onMounted(() => {
  if (props.visible) {
    loadStatistics();
  }
});
</script>

<style scoped>
.statistics-content {
  max-height: 600px;
  overflow-y: auto;
}

.basic-statistics,
.status-distribution,
.usage-statistics {
  margin-bottom: 30px;
}

.basic-statistics h3,
.status-distribution h3,
.usage-statistics h3 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stat-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  background: #f8f9fa;
  border-left: 4px solid #409eff;
  border-radius: 8px;
}

.stat-card.enabled {
  border-left-color: #67c23a;
}

.stat-card.disabled {
  border-left-color: #f56c6c;
}

.stat-card.used {
  border-left-color: #e6a23c;
}

.stat-card.unused {
  border-left-color: #909399;
}

.stat-value {
  margin-bottom: 4px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.distribution-chart {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.distribution-item {
  display: flex;
  gap: 12px;
  align-items: center;
}

.distribution-bar {
  flex: 1;
  height: 20px;
  overflow: hidden;
  background: #f0f2f5;
  border-radius: 10px;
}

.bar-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.bar-fill.enabled {
  background: #67c23a;
}

.bar-fill.disabled {
  background: #f56c6c;
}

.distribution-info {
  display: flex;
  gap: 8px;
  align-items: center;
  min-width: 150px;
}

.status-name {
  font-weight: 500;
  color: #303133;
}

.status-count {
  font-weight: 600;
  color: #409eff;
}

.status-percentage {
  font-size: 12px;
  color: #909399;
}

.usage-table {
  max-height: 300px;
  overflow-y: auto;
}

.category-name {
  display: flex;
  gap: 8px;
  align-items: center;
}

.article-count {
  font-weight: 600;
  color: #303133;
}

.published-count {
  font-weight: 500;
  color: #67c23a;
}

.draft-count {
  font-weight: 500;
  color: #e6a23c;
}

.no-data {
  font-style: italic;
  color: #c0c4cc;
}

.usage-rate {
  width: 130px;
  margin: 0 auto;
}

/* 合并重复的选择器，避免 stylelint 警告 */
.usage-rate :deep(.el-progress-bar__outer) {
  position: relative;
  background-color: #f0f2f5;
  border-radius: 6px;
}

.usage-rate :deep(.el-progress-bar__inner) {
  min-width: 20px; /* 确保至少有最小宽度 */
  border-radius: 6px;
  transition: width 0.3s ease;
}

.usage-rate :deep(.el-progress__text) {
  min-width: auto !important;
  padding: 0 4px;
  font-size: 12px !important;
  font-weight: 600 !important;
  line-height: 1;
  color: #fff !important;
  text-shadow: 0 1px 2px rgb(0 0 0 / 50%);
}

/* 低百分比时的外部文字样式 */
.usage-rate.low-percentage {
  position: relative;
}

.usage-rate .external-text {
  position: absolute;
  top: 50%;
  right: -35px;
  font-size: 12px;
  font-weight: 600;
  color: #606266;
  white-space: nowrap;
  transform: translateY(-50%);
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
